package com.chris.easymallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chris.common.to.SkuFullReductionTo;
import com.chris.common.to.SpuBoundsTo;
import com.chris.common.utils.R;
import com.chris.common.validator.Assert;
import com.chris.easymallproduct.dto.*;
import com.chris.easymallproduct.entity.*;
import com.chris.easymallproduct.feign.CouponFeignService;
import com.chris.easymallproduct.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chris.common.utils.PageUtils;
import com.chris.common.utils.Query;

import com.chris.easymallproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService descService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;


    //todo 需要将查询条件封装  目前存在的问题，getPageWrapper()方法需要返回的是整体带括号，区分后面and的优先级
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> pageWrapper = new Query<SpuInfoEntity>().getPageWrapper(params, SpuInfoEntity.class);
        Object status = params.get("status");
        LambdaQueryWrapper<SpuInfoEntity> lambda = pageWrapper.lambda();
        if (status != null) {
            lambda.eq(SpuInfoEntity::getPublishStatus, status);
        }
        Object brandId = params.get("brandId");
        if (brandId != null) {
            lambda.eq(SpuInfoEntity::getBrandId, brandId);
        }
        Object catelogId = params.get("catelogId");
        if (catelogId != null) {
            lambda.eq(SpuInfoEntity::getCatalogId, catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), pageWrapper);
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SpuInfoDto spuInfo) {

        //首先保存spu信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();
        //保存商品描述图片（商品介绍里面）
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", decript));
        descService.saveInfo(spuInfoDescEntity);
        //保存商品图集（主页上面）
        List<String> images = spuInfo.getImages();
        spuImagesService.saveInfo(spuId, images);
        //保存spu的规格参数
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        productAttrValueService.saveInfo(spuId, baseAttrs);
        //保存SKU信息
        List<Skus> skus = spuInfo.getSkus();
        skus.forEach(item -> {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(item, skuInfoEntity);
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(spuId);
            String defaultImageUrl = "";
            List<Images> imagesList = item.getImages();
            for (Images img : imagesList) {
                if (1 == img.getDefaultImg()) {
                    defaultImageUrl = img.getImgUrl();
                    break;
                }
            }
            skuInfoEntity.setSkuDefaultImg(defaultImageUrl);
            //保存sku的信息
            skuInfoService.saveInfo(skuInfoEntity);

            //保存sku的展示图片
            List<SkuImagesEntity> skuImagesEntities = imagesList.stream().map(img -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setImgUrl(img.getImgUrl());
                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuImagesEntity;
            }).filter(skuImagesEntity -> StringUtils.isNotBlank(skuImagesEntity.getImgUrl())
            ).collect(Collectors.toList());
            skuImagesService.saveInfo(skuImagesEntities);
            //保存sku的属性
            List<Attr> attrs = item.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveInfo(skuSaleAttrValueEntities);

            //sku的优惠信息
            SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
            BeanUtils.copyProperties(item, skuFullReductionTo);
            skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
            if (item.getFullCount() != null && skuFullReductionTo.getFullCount() > 0 || skuFullReductionTo.getFullPrice() != null && BigDecimal.ZERO.compareTo(skuFullReductionTo.getFullPrice()) < 0) {
                R r = couponFeignService.saveSkuFullReduction(skuFullReductionTo);
                Assert.isFalse(R.isOk(r), "保存失败");
            }

        });

        //保存spu的积分情况
        Bounds bounds = spuInfo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);

        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        Assert.isFalse(R.isOk(r), "保存失败");
    }

}